package com.fyzk.chart;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.tyjc.unique.util.ScreenUtils;
import com.fyzk.activity.myview.DrawBallFrameLayout;
import com.fyzk.bean.MissValueListBean;
import com.tyjc.lottery.R;
import com.fyzk.utils.LogUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fanxs11 on 17/6/5.
 */

public class ChartBaseView extends DrawBallFrameLayout {

    private static final int STATE_NORMAL = 0;      // 数据正常
    private static final int STATE_REQUESTING = 1;  // 数据获取中
    private static final int STATE_NODATA = 2;      // 无数据
    private static final int STATE_ERROR = 3;       // 请求数据失败（暂时不用）
    private int stateData = STATE_REQUESTING;

    private List<MissValueListBean.DataBean> infors = new ArrayList<>();
    private List<MissValueListBean.LabelBean> labels = new ArrayList<>();
    private int labelId = 0;

    private Context context;
    protected int screen_width, screen_height, screen_DPI;
    protected float screen_density;
    protected static final float count = 13;//一屏幕可布置小球的个数（以此求单位宽度）
    protected float unitLength = 10;//单位宽度（高度）
    protected int column = 13;//列数
    protected int row = 0;//行数
    protected float totalWidth = 100;//画布总宽度
    protected float totalHeight = 100;//画布总高度

    private Paint bgPaint;
    private Paint linePaint;
    private Paint textPaint;
    private Paint zheXianPaint;

    private int color_bg_h;//灰
    private int color_top_bg_h;//灰
    private int color_bg_w;//白
    private int color_line;
    private int color_text1;
    private int color_red;
    private int color_zhexian;

    private Bitmap qiu_btm;
    private int startNum = 1;
    public boolean isShowZheXian = false;

    private float leftWidth = 0;
    private float topHeight = 0;

    private int padding = 5;
//    private int this.getScrollY() = 0;

//    public ChartBaseView(Context context) {
//        super(context);
//        init(context);
//    }

    public ChartBaseView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

//    public ChartBaseView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
//        super(context, attrs, defStyleAttr);
//        init(context);
//    }

    protected void init(Context context){
        setWillNotDraw(false);
        if (isInEditMode()) {
            return;
        }
        this.context = context;

        this.screen_width = ScreenUtils.getInstance().getWidth();
        this.screen_height = ScreenUtils.getInstance().getHeight();
        this.screen_DPI = ScreenUtils.getInstance().getDensityDPI();
        this.screen_density = ScreenUtils.getInstance().getDensity();

        unitLength = screen_width / count;
        totalWidth = screen_width;
        totalHeight = screen_width;     // 默认高度 与 宽度相同
        leftWidth = unitLength*2;
        topHeight = unitLength;
        padding = (int)(unitLength/10);

        color_bg_h = context.getResources().getColor(R.color.bgh_c);
        color_top_bg_h = context.getResources().getColor(R.color.qianhui2);
        color_bg_w = context.getResources().getColor(R.color.bgb);
        color_line = context.getResources().getColor(R.color.shu_line);
        color_text1 = context.getResources().getColor(R.color.zi_c);
        color_red = context.getResources().getColor(R.color.red_packet);
        color_zhexian = context.getResources().getColor(R.color.red_packet);

        bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        bgPaint.setAntiAlias(true);
        bgPaint.setColor(color_bg_w);

        linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        linePaint.setAntiAlias(true);
        linePaint.setColor(color_line);
        linePaint.setStrokeWidth(1);

        textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setAntiAlias(true);
        textPaint.setColor(color_text1);
        textPaint.setTextSize(16 * screen_density);

        zheXianPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        zheXianPaint.setAntiAlias(true);
        zheXianPaint.setColor(color_zhexian);
        zheXianPaint.setStrokeWidth(5);

        qiu_btm = BitmapFactory.decodeResource(context.getResources(), R.drawable.hongqiu_check);

        setFocusable(true);
    }

//    @Override
//    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        // TODO Auto-generated method stub
//        int width = (int)this.totalWidth;
//        int height = (int)this.totalHeight;
//        setMeasuredDimension(width, height);
//    }

    MissValueListBean.LabelBean chooseLabel;
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x = 0;
        int y = 0;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                x = (int)event.getX();
                y = (int)event.getY()+this.getScrollY();
                for (int i = 0; i < labels.size(); i++) {
                    LogUtil.d("点击0 "+labels.get(i).isCheck);
                    if (labels.get(i).isCheck) {
                        labelId = i;
                        continue;
                    }
                    if (labels.get(i).rect != null && labels.get(i).rect.contains(x,y)){
                        LogUtil.d("点击1");
                        chooseLabel = labels.get(i);
                        labelId = i;
                        break;
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:

                break;
            case MotionEvent.ACTION_UP:
                x = (int)event.getX();
                y = (int)event.getY()+this.getScrollY();
                if (chooseLabel != null && chooseLabel.rect.contains(x, y)) {
                    for (int i = 0; i < labels.size(); i++) {
                        labels.get(i).isCheck =false;
                    }
                    LogUtil.d("点击2");
                    chooseLabel.isCheck = true;
                    isClickTrend = false;
                    this.invalidate();
                } else {
                    labelId = chooseLabel != null ? chooseLabel.id : 0;
                }
                break;
        }
        return super.onTouchEvent(event);
    }

    /**
     * 清除
     * @param canvas
     */
    private void clear(Canvas canvas) {
        Paint paint = new Paint();
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        canvas.drawPaint(paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        clear(canvas);
//        canvas.drawColor(Color.WHITE);
        switch (stateData) {
            case STATE_REQUESTING:
                canvas.drawColor(Color.WHITE);
                Rect rect = new Rect(0, this.getScrollY(), (int)totalWidth, (int)totalHeight/2+this.getScrollY());
                textPaint.setColor(color_text1);
                drawText(canvas, textPaint, "数据获取中...", rect);
                break;
            case STATE_NODATA:
            case STATE_ERROR:
                canvas.drawColor(Color.WHITE);
                textPaint.setColor(color_text1);
                Rect rect_no = new Rect(0, this.getScrollY(), (int)totalWidth, (int)totalHeight/2+this.getScrollY());
                drawText(canvas, textPaint, "暂无数据!", rect_no);
                break;
            default:
                drawTop(canvas);
                drawLeft(canvas);
                drawCenter(canvas);
                break;
        }
        canvas.drawLine(0, 0, screen_width, 0, linePaint);
    }

    protected void drawTop(Canvas canvas) {
        bgPaint.setColor(color_bg_w);
        Rect topBgRect = new Rect(0,this.getScrollY(),screen_width, (int)(topHeight+this.getScrollY()));
        canvas.drawRect(topBgRect, bgPaint);
        if (topHeight > unitLength) {
            float topItemW = (screen_width - leftWidth) / labels.size();
            for (int i = 0; i < labels.size(); i++) {
                int x0 = (int)(topItemW*i+leftWidth);
                int x1 = (int)(topItemW*(i+1)+leftWidth);
                int y0 = topBgRect.top;
                int y1 = (int)(topBgRect.top+unitLength);
                Rect rect = new Rect(x0, y0, x1, y1);
                labels.get(i).rect = rect;
                if (labels.get(i).isCheck) {
                    textPaint.setColor(color_red);
//                    canvas.drawBitmap(topItem_bg, null, rect, bgPaint);
                    linePaint.setStrokeWidth(4);
                    linePaint.setColor(color_red);
                    canvas.drawLine(rect.left, rect.bottom-1, rect.right, rect.bottom, linePaint);
                    linePaint.setStrokeWidth(1);
                    linePaint.setColor(color_line);
                } else {
                    textPaint.setColor(color_text1);
                }
                String text = labels.get(i).showLabel;
                drawText(canvas, textPaint, text, rect);
                canvas.drawLine(rect.left, rect.top, rect.left, rect.bottom, linePaint);
            }

        } else {
//            topHeight = 1;
        }
        textPaint.setColor(color_text1);
        for (int j = 0; j < column; j++) {
            String text = "";
            int x0 = (int) (unitLength * (j) + leftWidth);
            int x1 = (int) (unitLength * (j + 1) + leftWidth);
            int y0 = (int) (topBgRect.bottom-unitLength);
            int y1 = (int) topBgRect.bottom;
            Rect rect = new Rect(x0, y0, x1, y1);

            bgPaint.setColor(color_top_bg_h);
            canvas.drawRect(rect, bgPaint);
            text = j < 10 ? "0"+(j+1) : ""+(j+1);
            drawText(canvas, textPaint, text, rect);
            canvas.drawLine(x0, y0, x0, y1, linePaint);
            canvas.drawLine(x0, y0, x1, y0, linePaint);
        }
        linePaint.setStrokeWidth(2);
        linePaint.setColor(color_line);
        canvas.drawLine(topBgRect.left, topBgRect.top, topBgRect.right, topBgRect.top, linePaint);
        canvas.drawLine(topBgRect.left, topBgRect.bottom, topBgRect.right, topBgRect.bottom, linePaint);
        linePaint.setStrokeWidth(2);
        linePaint.setColor(color_line);
    }

    protected void drawLeft(Canvas canvas) {
        textPaint.setColor(color_text1);
        for (int i = 0; i < row; i++) {

            Rect rectPhase = new Rect(0, (int)(unitLength*i+topHeight+this.getScrollY()), (int)(unitLength*2), (int)(unitLength*(i+1)+topHeight+this.getScrollY()));
            //绘制背景颜色
            if (i % 2 != 0) {
                bgPaint.setColor(color_bg_h);
            }else {
                bgPaint.setColor(color_bg_w);
            }
            canvas.drawRect(rectPhase, bgPaint);

            String phase = infors.get(i).getPhase();
            phase = phase.substring(phase.length()-2,phase.length());
            drawText(canvas, textPaint, phase+"期", rectPhase);
        }
    }

    protected void drawCenter(Canvas canvas) {
//        Log.e("ondraw_center", "column= "+column);
        Rect rect;
        List<Rect> rects = new ArrayList<Rect>();
        List<Integer> haoMas = new ArrayList<Integer>();

        String label = "";
        if (labelId >= labels.size()) {
            label = labels.get(0).label;
        } else {
            label = labels.get(labelId).label;
        }
        for (int i = 0; i < row; i++) {

            for (int j = 0; j < column; j++) {
                String text = "";
                text = infors.get(i).missNums(label)[j]+"";
                int x0 = (int)(unitLength*(j)+leftWidth);
                int x1 = (int)(unitLength*(j+1)+leftWidth);
                int y0 = (int)(unitLength*i+topHeight+this.getScrollY());
                int y1 = (int)(unitLength*(i+1)+topHeight+this.getScrollY());
                rect = new Rect(x0, y0, x1, y1);

                //绘制背景颜色
                if (i % 2 != 0) {
                    bgPaint.setColor(color_bg_h);
                }else {
                    bgPaint.setColor(color_bg_w);
                }
                canvas.drawRect(rect, bgPaint);

                //绘制线条
//                    if (j != 0) {
//                    }
                canvas.drawLine(x0, y0, x0, y1, linePaint);

                //绘制小球背景图片
                if (text.equals("0")) {
                    rects.add(new Rect(rect.left+padding,rect.top+padding,rect.right-padding,rect.bottom-padding));
                    haoMas.add(j+startNum);
                }else{
                    textPaint.setColor(color_text1);
                    drawText(canvas, textPaint, text, rect);
                }

            }

        }

        //画球
        for (int k = 0; k < rects.size(); k++) {
            if (isShowZheXian && k < (rects.size()-1)) {

                zheXianPaint.setStrokeWidth((float)2.5);//1.0为正常粗细
                canvas.drawLine(rects.get(k).centerX(), rects.get(k).centerY(), rects.get(k+1).centerX(), rects.get(k+1).centerY(), zheXianPaint);
            }

            canvas.drawBitmap(qiu_btm, null, rects.get(k), bgPaint);
            textPaint.setColor(color_bg_w);
            if (haoMas.get(k) < 10) {

                drawText(canvas, textPaint, "0"+haoMas.get(k), rects.get(k));
            }else {
                drawText(canvas, textPaint, ""+haoMas.get(k), rects.get(k));
            }
        }
    }

    /**
     * 绘制文字
     * @param canvas
     * @param paint
     * @param text
     * @param rect
     */
    protected void drawText(Canvas canvas, Paint paint, String text, Rect rect){
        Paint.FontMetrics fm = paint.getFontMetrics();
        int baseLine = (int)(rect.top + (rect.bottom - rect.top - fm.bottom + fm.top) / 2 - fm.top);
        canvas.drawText(text, rect.centerX() - (paint.measureText(text)/2), baseLine, paint);
    }

    public List<MissValueListBean.DataBean> getInfors() {
        return infors;
    }

    public void setInfors(List<MissValueListBean.DataBean> infors, String[] labels) {
        if (labels == null || labels.length == 0) {
            labels = new String[]{"miss"};
        }
        if (infors != null && infors.size() > 0) {
            stateData = STATE_NORMAL;
            this.infors = infors;
            this.labels.clear();
            if (labels.length == 1) {
                this.labels.add(new MissValueListBean.LabelBean(0, labels[0], "万位"));
            }
            if (labels.length == 2) {
                this.labels.add(new MissValueListBean.LabelBean(0, labels[0], "万位"));
                this.labels.add(new MissValueListBean.LabelBean(1, labels[1], "千位"));
            }
            if (labels.length == 3) {
                this.labels.add(new MissValueListBean.LabelBean(0, labels[0], "万位"));
                this.labels.add(new MissValueListBean.LabelBean(1, labels[1], "千位"));
                this.labels.add(new MissValueListBean.LabelBean(2, labels[2], "百位"));
            }
            isShowZheXian = this.labels.size() > 1;
            int checkId = chooseLabel != null ? chooseLabel.id : 0;
            if (checkId >= this.labels.size()) {
                checkId = 0;
            }
            this.labels.get(checkId).isCheck = true;
            column = infors.get(0).missNums(labels[0]).length;
            row = infors.size();

            totalWidth = unitLength * column+leftWidth;
            totalHeight = unitLength * row;
            topHeight = labels.length > 1 ? unitLength*2 : unitLength;
            totalHeight += topHeight;
            if (totalHeight < totalWidth*2.0/3) {
                totalHeight = (float)(totalWidth*2.0/3);
            }

//            setMeasuredDimension((int)totalWidth, (int)totalHeight);
        } else {
            stateData = STATE_NODATA;
        }
        this.downY = (int)totalHeight;
        if (state == STATE_DOWN) {
            this.scrollTo(0,-downY);
        }

        this.invalidate();
    }

    public float getTotalHeight() {
        return totalHeight;
    }

    public void requestingData() {
        stateData = STATE_REQUESTING;
        this.invalidate();
    }
    public void noData() {
        stateData = STATE_NODATA;
        this.invalidate();
    }

    public void errorData() {
//        stateData = STATE_ERROR;
        stateData = STATE_NODATA;
        this.invalidate();
    }
}
